import {
  saveRwaljApi,
  getRwaljPageApi,
  deleteRwaljDataApi,
  ImportRwaljDataApi,
  saveRwalDataApi,
  updateRwalDataApi,
  updateRwaljApi,
  deleteSubRwalApi,
  mergeSubRwalApi,
  rwalPageApi,
  exportRwaljDataApi,
  getRwaljCountApi
} from './api'
import { connectWebSocket } from '@/utils/web-socket'
import { PriorityOptions } from '@/assets/data/pathInfo'
import { subJcybPageApi } from '@/views/sampleManagement/decision/api'
import { saveAs } from 'file-saver'
import moment from 'moment'

export default {
  components: {},
  data() {
    return {
      PriorityOptions,
      tableLoading: true,
      formInline: {
        demand: '',
        targetArea: '',
        sample: ''
      },
      // 优先级
      yxjOption: [
        {
          value: '高',
          label: '高'
        },
        {
          value: '低',
          label: '低'
        }
      ],
      tableData: [],
      currentPage3: 5,
      dialogVisible: false,
      importVisible: false,
      labelPosition: 'right',
      formLabelAlign: {
        name: '',
        region: '',
        type: ''
      },
      taskCaseBool: 0,
      pageCurrent: 1,
      pageSize: 10,
      total: 0,
      multipleSelection: [],
      rwTableKey: 0,
      rwInputData: [],
      rwalImportState: false,
      rules: {
        yrwID: [
          { required: true, message: '请输入任务案例编号', trigger: 'blur' }
        ],
        wxbs: [{ required: true, message: '请输入卫星标识', trigger: 'blur' }],
        gckssj: [
          { required: true, message: '请输入观测开始时间', trigger: 'change' }
        ],
        gcjssj: [
          { required: true, message: '请输入观测结束时间', trigger: 'change' }
        ],
        jd: [{ required: true, message: '请输入经度', trigger: 'blur' },
        {
          validator: this.jdCoolarInfo,
          message: '经度格式不正确',
          trigger: 'blur'
        }
        ],
        cbj: [{ required: true, message: '请输入侧摆角', trigger: 'blur' }],
        cgqbs: [
          { required: true, message: '请输入传感器标识', trigger: 'blur' }
        ],
        yxj: [{ required: true, message: '请选择优先级', trigger: 'change' }],
        zxdfwsk: [
          { required: true, message: '请输入中心点访问时刻', trigger: 'blur' }
        ],
        wd: [{ required: true, message: '请输入纬度', trigger: 'blur' },
        {
          validator: this.wdCoolarInfo,
          message: '纬度格式不正确',
          trigger: 'blur'
        }
        ],
        tygdj: [
          { required: true, message: '请输入太阳高度角', trigger: 'blur' }
        ],
        jcybjID: [
          { required: true, message: '请输入任务案例集编号', trigger: 'blur' }
        ],
        rwssdlqy: [
          { required: true, message: '请输入任务所属地理区域', trigger: 'blur' }
        ],
        rwcj: [{ required: true, message: '请输入任务场景', trigger: 'blur' }]
      },
      sfRwalj: true,
      mergeRwalState: false,
      ssjcybjID: 0,
      subCurtent: 1,
      subSize: 20,
      subtotal: 0,
      rowKeyId: [],
      dialogCurtent: 1,
      dialogSize: 100,
      dialogtotal: 0,
      jxtableLoading: false,
      taskCaseTotal: 0,
      fileRef: null
    }
  },
  computed: {},
  created() { },
  watch: {
    // 监听开始时间和结束时间的变化，以重新计算中间时间
    'formLabelAlign.gckssj': {
      handler() {
        this.calculateMiddleTime()
      }
    },
    'formLabelAlign.gcjssj': {
      handler() {
        this.calculateMiddleTime()
      }
    }
  },
  mounted() {
    const page = {
      pageCurrent: this.pageCurrent,
      pageSize: this.pageSize
    }
    this.getRwalPageData(page)
    this.wsImportRwalj()
    this.mergeWsRwalj()
    this.getRwaljCount()
  },
  methods: {

    // 获取任务案例总数
    getRwaljCount() {
      getRwaljCountApi().then((res) => {
        if (res.data.code === 200) {
          this.taskCaseTotal = res.data.data
        }
      })
    },

    // 效验经度坐标格式
    jdCoolarInfo(rule, value, callback) {
      const coordinateRegex = /^[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/;
      if (coordinateRegex.test(value)) {
        callback();
      }
      else {
        callback(new Error('经度格式不正确'))
      }
    },
    // 效验纬度坐标格式
    wdCoolarInfo(rule, value, callback) {
      const coordinateRegex = /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?)$/;
      if (coordinateRegex.test(value)) {
        callback();
      }
      else {
        callback(new Error('经度格式不正确'))
      }
    },

    handleImportTaskCase() {
      this.importVisible = true
    },
    dialogHandleCurrentChange(val) {
      this.dialogCurtent = val
      this.jxExcelFile()
    },
    calculateMiddleTime() {
      if (this.formLabelAlign.gckssj && this.formLabelAlign.gcjssj) {
        // 将字符串转换为Date对象
        const startDate = new Date(this.formLabelAlign.gckssj)
        const endDate = new Date(this.formLabelAlign.gcjssj)

        // 计算时间差（毫秒）
        const diff = endDate - startDate

        // 计算中间时间
        const middleDate = new Date(startDate.getTime() + diff / 2)
        // 使用momentDate格式化日期
        var momentDate = moment.parseZone(middleDate)
        // 格式化为YYYY-MM-DD HH:mm:ss
        var formattedDate = momentDate.format('YYYY-MM-DD HH:mm:ss')
        // 将格式化后的日期赋值给formLabelAlign.zxdfwsk
        this.formLabelAlign.zxdfwsk = formattedDate
      } else {
        this.formLabelAlign.zxdfwsk = ''
      }
    },
    // 导出任务案例
    async handleExportTaskCase() {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请选择要导出的数据')
      }
      if (this.multipleSelection.length > 1) {
        return this.$message.warning('每次只可以导出一条数据')
      }

      this.$message.warning("正在导出")
      const rowValue = this.multipleSelection[0]

      try {
        const response = await exportRwaljDataApi({
          id: rowValue.id
        })

        saveAs(
          response.data,
          `${rowValue.jcybjID}-${rowValue.rwcj}-${rowValue.rwssdlqy}.xlsx`
        )
      } catch (error) {
        console.error('下载Excel失败:', error)
        this.$message.error("导出失败")
      }
    },
    // 控制每次只能展开一个表格
    handleExpendChange(row) {
      if (!this.rowKeyId[0] || row.id !== this.rowKeyId[0]) {
        this.rowKeyId = []
        this.rowKeyId.push(row.id)
      } else {
        this.rowKeyId = []
      }
      this.ssjcybjID = row.id
      this.subCurtent = 1
      this.subSize = 20
      this.subRwalPageData()
    },
    subRwalPageData() {
      const data = {
        ssjcybjID: this.ssjcybjID,
        pageCurrent: this.subCurtent,
        pageSize: this.subSize
      }
      rwalPageApi(data).then(res => {
        if (res.data.code === 200) {
          this.tableData.forEach((item, index) => {
            if (item.id === this.ssjcybjID) {
              this.tableData[index].rwalList = res.data.data.records
              this.subtotal = res.data.data.total
            }
          })
        }
      })
    },
    SubHandleSizeChange(val) {
      this.subSize = val
      this.subRwalPageData()
    },
    SubHandleCurrentChange(val) {
      this.subCurtent = val
      this.subRwalPageData()
    },
    // 合并任务案例集
    mergeRwalj() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择需要合并的任务案例!')
        return
      }
      if (this.multipleSelection.length < 2) {
        return this.$message.warning('至少选择两个任务案例!')
      }
      let rwaljID = ''
      let flag = false
      this.multipleSelection.forEach(item => {
        rwaljID = rwaljID + item.id + ','
        if (!item.rwalState || item.rwalState != '1') {
          flag = true
        }
      })
      if (flag) {
        return this.$message.warning('所选的任务案例集下无任务!')
      }
      const data = {
        jcybjID: rwaljID
      }
      mergeSubRwalApi(data).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功!')
          this.mergeRwalState = false
          this.tableLoading = true
          this.mergeLxRwalj()
        } else {
          this.$message.error('操作失败!')
        }
      })
    },
    // 轮询任务案例集合并
    mergeLxRwalj() {
      let count = 0
      const invalid = setInterval(() => {
        if (count > 10 || this.mergeRwalState) {
          this.$message.success('合并完成！')
          this.getRwalPageData(this.formInline)
          clearInterval(invalid)
        } else {
          this.$message.warning('正在合并数据，请稍后！')
        }
        count++
      }, 2500)
    },
    // ws监听决策样本合并是否完成
    mergeWsRwalj() {
      connectWebSocket({
        url: window.ipConfig.wsUrl,
        topic: [
          {
            name: '/topic/merageRwalj',
            callback: res => {
              this.mergeRwalState = true
            }
          }
        ]
      })
    },
    // 添加任务案例
    createSubRwalData(val) {
      this.formLabelAlign = {}
      this.dialogVisible = true
      this.taskCaseBool = 1
      this.sfRwalj = false
      this.formLabelAlign.ssjcybjID = val.id
    },
    // 编辑任务案例集
    aggregateEdit(val) {
      this.formLabelAlign = {}
      this.taskCaseBool = 0
      this.sfRwalj = true
      this.dialogVisible = true
      this.getFormValueByKey(val)
    },
    // 编辑任务案例
    sampleEdit(val) {
      this.taskCaseBool = 0
      this.sfRwalj = false
      this.dialogVisible = true
      this.getFormValueByKey(val)
    },
    // 删除任务案例
    deleteSubRwalData(row) {
      const data = {
        ids: [row.id]
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        deleteSubRwalApi(data).then(res => {
          if (res.data.code === 200) {
            this.$message.success('操作成功')
            this.pageCurrent = 1
            this.subCurtent = 1
            this.rowKeyId = []
            this.getRwalPageData(this.formInline)
          } else {
            this.$message.error('操作失败')
          }
        })
      })
    },
    // 根据表单key赋值
    getFormValueByKey(val) {
      Object.keys(val).forEach(key => {
        this.$set(this.formLabelAlign, key, val[key])
      })
    },
    uploadFileChange(event) {
      let that = this
      console.log('111111111111111')
      if (event.target.files.length > 0) {
        console.log('22222222222')
        const file = event.target.files[0]
        that.formInline.demand = file.name
        that.$set(that.formInline, 'demand', file.name)
      }

    },
    // 选择需要导入的文件
    selectWjButton() {
      let that = this
      if (that.fileRef) {
        that.fileRef.remove() // 上传完成后，删除这个DOM元素
      }
      // 创建一个input标签
      that.fileRef = document.createElement('input')
      // 设置input标签的属性
      that.fileRef.name = 'file'
      // 设置input标签的样式
      that.fileRef.type = 'file'
      // 设置input标签的属性
      that.fileRef.accept = '.xls,.xlsx'
      // 设置input标签的样式
      that.fileRef.style.display = 'none'
      // 将input标签添加到body中
      that.fileRef.click()
      document.body.appendChild(that.fileRef)
      // 监听用户选择文件后的操作
      that.fileRef.addEventListener('change', that.uploadFileChange, false)
      // let that = this
      // let csMax = 0
      // function callbackFn(event) {
      //   if (csMax === 0) {
      //     if (event.target.files.length > 0) {
      //       const file = event.target.files[0]
      //       that.formInline.demand = file.name
      //       console.log('1111111111111', that.formInline.demand)
      //       csMax = 1
      //     }
      //   }
      // }
      // const changeFile = document.getElementById('fileUpload')
      // changeFile.removeEventListener('change', callbackFn, false)
      // changeFile.click()
      // // 监听文件选择变化
      // changeFile.addEventListener('change', callbackFn, false)
      // console.log('1111111111111', this.formInline.demand)
    },
    // 解析excel文件
    jxExcelFile() {
      this.jxtableLoading = true
      const fileInput = this.fileRef
      if (fileInput.files.length > 0) {
        const file = fileInput.files[0]
        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', '1')
        formData.append('pageCurrent', this.dialogCurtent)
        formData.append('pageSize', this.dialogSize)
        ImportRwaljDataApi(formData).then(res => {
          if (res.data.code === 200) {
            const data = res.data
            this.rwInputData[0] = data.data
            this.dialogtotal = data.data.rwansl
            this.rwTableKey = Math.random()
            this.$message.success('操作成功!')
            this.jxtableLoading = false
            // 上传文件有脏数据，提示用户
            if (res.data.data.errResult.errNum > 0) {
              this.showErrorMessages(res.data.data.errResult)
            }
            fileInput.remove() // 上传完成后，删除这个DOM元素
          } else {
            this.$message.error('操作失败！')
            this.jxtableLoading = false
          }
        })
      }
    },
    // 显示上传的错误信息
    showErrorMessages(errorMsgs) {
      const errorMessageList = errorMsgs.errMsg

      errorMessageList.unshift(
        `错误信息`
      )

      errorMessageList.unshift(
        `错误条数：${errorMsgs.errNum} 条`
      )

      errorMessageList.unshift(
        `总条目数：${errorMsgs.total} 条`
      )

      const errorMessageElements = errorMessageList.map((message, index) => (
        `<div>${message}</div>`
      )).join("")

      this.$alert(errorMessageElements, '提示', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true
      })
    },
    // 提交解析后的数据保存
    jxCommitData() {
      if (this.rwInputData.length === 0) {
        this.$message.warning('请先上传文件并解析')
        return
      }
      this.$message.warning("正在导入")
      this.tableLoading = true
      const fileInput = this.fileRef
      if (fileInput.files.length > 0) {
        const file = fileInput.files[0]
        const formData = new FormData()
        formData.append('file', file)
        formData.append('type', '2')
        ImportRwaljDataApi(formData).then(res => {
          if (res.data.code === 200) {
            this.$message.success('操作成功')
            this.rwalImportState = false
            this.lxImportMethod()
          } else {
            this.$message.error(res.data.message != null ? res.data.message : '操作失败')
            this.tableLoading = false
          }
        })
        this.rwInputData = []
        this.importVisible = false
      }
    },
    // ws监听任务案例导入是否完成
    wsImportRwalj() {
      connectWebSocket({
        url: window.ipConfig.wsUrl,
        topic: [
          {
            name: '/topic/rwaljImport',
            callback: res => {
              this.rwalImportState = true
            }
          }
        ]
      })
    },
    // 轮询查看导入任务案例是否完成
    lxImportMethod() {
      let count = 0
      const invalid = setInterval(() => {
        if (count > 10 || this.rwalImportState) {
          this.$message.success('导入完成！')
          this.getRwalPageData(this.formInline)
          clearInterval(invalid)
        } else {
          this.$message.warning('正在导入数据，请稍后！')
        }
        count++
      }, 2500)
    },
    jxCancell() {
      document.getElementById('fileForm').reset()
      this.formInline.demand = ''
      this.rwInputData = []
      this.importVisible = false
    },
    // 批量删除数据
    deleteAllSelectData(val) {
      const idList = []
      if (val.id) {
        idList[0] = val.id
      } else {
        this.multipleSelection.forEach(item => {
          idList.push(item.id)
        })
      }
      const data = {
        ids: idList
      }
      if (idList.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择删除项'
        })
        return false
      }

      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        deleteRwaljDataApi(data).then(res => {
          if (res.data.code === 200) {
            this.$message.success('操作成功')
            this.getRwalPageData(this.formInline)

          } else {
            this.$message.error('操作失败')
          }
        })
      })
    },
    //判断子数组中是否有数据，没有就不显示展开按钮
    iconHadler({ row }) {
      if (!row.rwalState || row.rwalState !== '1') {
        return 'icon-no'
      }
    },
    // 勾选回调方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 保存或更新任务案例集
    saveAndUpdateRwalData() {
      this.$refs.rwalForm.validate(valid => {
        if (valid) {
          this.pageCurrent = 1
          this.subCurtent = 1
          //任务案例集
          if (this.taskCaseBool === 1) {
            if (this.sfRwalj) {
              this.saveRwanlijData()
            } else {
              this.saveRwalData()
            }
          }
          // 任务案例子集
          else {
            if (this.sfRwalj) {
              this.updateMainRwaljData()
            } else {
              this.updateRwalData()
            }
          }
          this.dialogVisible = false
          this.rowKeyId = []
        }
      })
    },
    updateMainRwaljData() {
      updateRwaljApi(this.formLabelAlign).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功!')
          this.getRwalPageData(this.formInline)
        } else {
          this.$message.error('操作失败')
        }
      })
    },
    // 获取任务案例分页数据
    getRwalPageData(data) {
      this.tableLoading = true
      const query = {
        ...data,
        pageCurrent: this.pageCurrent,
        pageSize: this.pageSize
      }
      getRwaljPageApi(query).then(res => {
        if (res.data.code === 200) {
          const data = res.data
          this.tableData = data.data.records
          this.total = data.data.total
          this.tableLoading = false

        }
      })
      this.getRwaljCount()
    },
    // 保存任务案例集
    saveRwanlijData() {
      saveRwaljApi(this.formLabelAlign).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功!')
          this.getRwalPageData(this.formInline)
        } else {
          this.$message.error('操作失败')
        }
      })
    },
    saveRwalData() {
      saveRwalDataApi(this.formLabelAlign).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功!')
          this.getRwalPageData(this.formInline)
        } else {
          this.$message.error('操作失败')
        }
      })
    },
    updateRwalData() {
      updateRwalDataApi(this.formLabelAlign).then(res => {
        if (res.data.code === 200) {
          this.$message.success('操作成功!')
          this.getRwalPageData(this.formInline)
        } else {
          this.$message.error('操作失败')
        }
      })
    },
    // 筛选按钮
    onSubmit() {
      this.pageCurrent = 1
      this.getRwalPageData(this.formInline)
    },
    // 重置按钮
    cleanSubmit() {
      this.pageCurrent = 1
      this.formInline = {}
      this.getRwalPageData(this.formInline)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getRwalPageData(this.formInline)
    },
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.getRwalPageData(this.formInline)
    },
    /**
     * 默认为添加任务案例
     * @param val
     */
    addNewTaskCase(val) {
      this.taskCaseBool = val
      this.sfRwalj = true
      this.formLabelAlign = {}
      this.dialogVisible = true
      this.getFormValueByKey(val)
    },
    // 取消任务案例
    cancelRwalData() {
      this.$refs.rwalForm.resetFields()
      this.formLabelAlign = {}
      this.dialogVisible = false
    },
    // 判断弹窗显示名称
    getDialogTitle() {
      let strTitle = ''
      // 1新增 0编辑
      if (this.taskCaseBool === 1) {
        if (sfRwalj) {
          strTitle = '添加任务案例集'
        } else {
          strTitle = '添加任务案例'
        }
      } else {
        if (sfRwalj) {
          strTitle = '编辑任务案例集'
        } else {
          strTitle = '编辑任务案例'
        }
      }
      return strTitle
    }
  }
}
